package com.zjw.demo.vertx.starter.service.redis;

import com.zjw.demo.vertx.starter.annotation.NonNull;
import com.zjw.demo.vertx.starter.annotation.Nullable;
import com.zjw.demo.vertx.starter.annotation.core.Plugin;
import com.zjw.demo.vertx.starter.service.IService;
import com.zjw.demo.vertx.starter.utils.LogUtils;
import io.vertx.core.Vertx;
import io.vertx.redis.client.Redis;
import io.vertx.redis.client.RedisAPI;
import io.vertx.redis.client.RedisOptions;

public abstract class AbstractRedisService implements IService {

  private static final String TAG = "AbstractRedisService";
  @NonNull
  protected Redis client;

  @Nullable
  protected RedisAPI redisAPI;

  /**
   * 是否连接
   */
  protected boolean isConnect = false;

  @Override
  public void onStart(Vertx vertx) {
    RedisOptions options = new RedisOptions();

    for (String connect : requireConnectString()) {
      options.addConnectionString(connect);
    }

    onConnectBefore(options);

    client = Redis.createClient(vertx, options);
    client.connect().onComplete(event -> {
      if (event.succeeded()) {
        LogUtils.debug(TAG, "connect redis success");
        isConnect = true;
        redisAPI = RedisAPI.api(client);
        onConnectSuccess(client);
      } else {
        LogUtils.error(TAG, event.cause());
        onConnectFailed(event.cause());
        isConnect = false;
      }
    });
  }

  protected abstract String[] requireConnectString();

  protected abstract void onConnectBefore(RedisOptions options);

  protected abstract void onConnectSuccess(Redis client);

  protected abstract void onConnectFailed(Throwable throwable);
}
